<?php
declare (strict_types = 1);

namespace app\admin\model;


use app\admin\model\Role;
use app\admin\model\RolePermission;

class Permission extends BaseModel
{
    protected $table = 'permissions';
    protected $pk = 'id';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    
    // 字段类型转换
    protected $type = [
        'is_menu' => 'boolean',
        'status' => 'boolean',
        'sort_order' => 'integer',
        'parent_id' => 'integer',
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp'
    ];
    
    // 允许写入的字段
    protected $field = [
        'id', 'permission_name', 'permission_code', 'parent_id', 
        'module', 'controller', 'action', 'menu_icon', 'menu_url', 
        'is_menu', 'status', 'sort_order', 
        'created_at', 'updated_at'
    ];

    /**
     * 权限角色关联
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, RolePermission::class, 'role_id', 'permission_id');
    }

    /**
     * 状态获取器
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '禁用', 1 => '启用'];
        return $status[$data['status']] ?? '未知';
    }

    /**
     * 描述获取器 - 处理数据库中不存在description字段的情况
     */
    public function getDescriptionAttr($value, $data)
    {
        // 如果数据库中没有description字段，返回空字符串
        return $value ?? '';
    }

    /**
     * 是否菜单获取器
     */
    public function getIsMenuTextAttr($value, $data)
    {
        $isMenu = [0 => '否', 1 => '是'];
        return $isMenu[$data['is_menu']] ?? '否';
    }

    /**
     * 获取权限树
     */
    public static function getPermissionTree($parentId = 0)
    {
        $permissions = self::where('parent_id', $parentId)
                          ->where('status', 1)
                          ->order('sort_order', 'asc')
                          ->select();
        
        $tree = [];
        foreach ($permissions as $permission) {
            $item = [
                'id' => $permission->id,
                'title' => $permission->permission_name,
                'field' => 'permission_' . $permission->id,
                'spread' => true,
                'children' => self::getPermissionTree($permission->id)
            ];
            $tree[] = $item;
        }
        
        return $tree;
    }

    /**
     * 获取菜单权限树
     */
    public static function getMenuTree($parentId = 0)
    {
        $permissions = self::where('parent_id', $parentId)
                          ->where('is_menu', 1)
                          ->where('status', 1)
                          ->order('sort_order', 'asc')
                          ->select();
        
        $tree = [];
        foreach ($permissions as $permission) {
            $item = $permission->toArray();
            $item['children'] = self::getMenuTree($permission->id);
            $tree[] = $item;
        }
        
        return $tree;
    }

    /**
     * 获取权限列表
     */
    public static function getPermissionList($page = 1, $limit = 20, $where = [])
    {
        $query = self::order('sort_order', 'asc');
        
        // 添加搜索条件
        if (!empty($where['permission_name']) && is_array($where['permission_name'])) {
            $query->where('permission_name', $where['permission_name'][0], $where['permission_name'][1]);
        }
        if (!empty($where['module'])) {
            $query->where('module', $where['module']);
        }
        if (isset($where['is_menu']) && $where['is_menu'] !== '') {
            $query->where('is_menu', $where['is_menu']);
        }
        if (isset($where['status']) && $where['status'] !== '') {
            $query->where('status', $where['status']);
        }
        
        return $query->paginate([
            'list_rows' => $limit,
            'page' => $page
        ]);
    }

    /**
     * 获取所有启用的权限
     */
    public static function getEnabledPermissions()
    {
        return self::where('status', 1)
                   ->order('sort_order', 'asc')
                   ->select();
    }
}